<?php
	namespace Qzn\Model;
	class FileUploadHandler {
		private $m_regex = "/jpg|jpeg|gif|png/";
		private $m_dir = "./ProfilePic/";
		const EVERYTHING_WENT_BETTER_THEN_EXPECTED = 0;
		const GENERIC_ERROR = 1;
		const EXTENSION_NOT_SUPPORTED = 2;
		const FAILED_TO_MOVE = 3;
		const FILE_TO_BIG = 4;
		
		private $m_db = null;
		
		public function __construct(Database $db) {
			$this->m_db = $db;
		}
		
		/**
		 * Uploads a file
		 * @param binary $file
		 * @return int $errorCode
		 */
		public function UploadFile(Array $file, \Qzn\View\LoginView $lw) {
			$i = 0;
			$tempName;
			$ext;
			
			if ($file["error"] > 0) {
				return self::GENERIC_ERROR;
			}
			
			if ($file["size"] > 1048580) {
				return self::FILE_TO_BIG;
			}
			
			$ext = explode(".", $file["name"]);
			if (!preg_match($this->m_regex, end($ext))) {
				return self::EXTENSION_NOT_SUPPORTED;
			}
			
			$file["name"] = $lw->GetUserName().".".end($ext);
			
			if(end($ext) =="jpg" || end($ext) =="jpeg" ) {
				$src = imagecreatefromjpeg($file["tmp_name"]);
			}
			else if(end($ext) =="png") {
				$src = imagecreatefrompng($file["tmp_name"]);
			}
			else {
				$src = imagecreatefromgif($file["tmp_name"]);
			}
			
			list($width,$height)=getimagesize($file["tmp_name"]);
			
			$newWidth;
			$newHeight;
			if ($width > $height) {
				$newWidth = 200;
				$newHeight = ($height/$width) * $newWidth;
			} else {
				$newHeight = 200;
				$newWidth = ($width/$height) * $newHeight;
			}
			
			$tmp = imagecreatetruecolor($newWidth,$newHeight);
			
			imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
			
			$fn = $this->m_dir.$file["name"];
			
			if (end($ext) == "jpg" || end($ext) == "jpeg") {
				imagejpeg($tmp, $fn, 100);
			} else if (end($ext) == "png") {
				imagepng($tmp, $fn);
			} else {
				imagegif($tmp, $fn);
			}
			
			imagedestroy($src);
			imagedestroy($tmp);
			
			if (DatabaseQuery::SelectProfilePicture($lw->GetUserPk(), $this->m_db) != null) {
				DatabaseQuery::DeleteProfilePicture($lw->GetUserPk(), $this->m_db);
			}
			
			DatabaseQuery::InsertProfilePicture($lw->GetUserPk(), $this->m_dir.$file["name"], $this->m_db);

			return self::EVERYTHING_WENT_BETTER_THEN_EXPECTED;
		}
		
		/**
		 * Gets a list of files
		 * @return array files
		 */
		public function GetFileList() {
			$fileArray = null;
			$i = 0;
			
			if (is_dir($this->m_dir)) {
				if ($dh = opendir($this->m_dir)) {
					while (($file = readdir($dh)) !== false) {
						if (preg_match($this->m_regex, pathinfo($this->m_dir.$file, PATHINFO_EXTENSION))) {
							$fileArray[$i] = array($this->m_dir.$file, $file, pathinfo($this->m_dir.$file, PATHINFO_EXTENSION), strval(intval(filesize($this->m_dir.$file)/1024))." Kb");
							$i++;
						}
					}
					closedir($dh);
				}
			}
			
			return $fileArray;
		}
	}
?>